package com.mingmen.canting.zhenban;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mingmen.canting.R;
import com.mingmen.canting.adapter.MyLabelAdapter;
import com.mingmen.canting.adapter.ZhenBanSortAllLabelAdapter;
import com.mingmen.canting.adapter.ZhenBanSortLabelAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.chushizhang.ChushiZhangDanActivity;
import com.mingmen.canting.chushizhang.ChushiZhangRightFragment;
import com.mingmen.canting.definerecycleview.SwipeRecyclerView;
import com.mingmen.canting.defineview.PayPassDialog;
import com.mingmen.canting.defineview.PayPassView;
import com.mingmen.canting.dialog.ButtomDialogView;
import com.mingmen.canting.fragment.BaseFragment;
import com.mingmen.canting.http.MyOkhttp;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.AppConfig;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.BeiZhuModel;
import com.mingmen.canting.model.ChushiZhangRight;
import com.mingmen.canting.model.CommdityColletModel;
import com.mingmen.canting.model.GetMarkModel;
import com.mingmen.canting.model.LinkLabelBean;
import com.mingmen.canting.model.ObjectResult;
import com.mingmen.canting.model.ShopListModel;
import com.mingmen.canting.model.SubMitModel;
import com.mingmen.canting.model.ZhenBanSortDetail;
import com.mingmen.canting.popwindow.PopupWindowCompat;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;
import com.mingmen.canting.zhenbanlibrary.ClassifyNewAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class ZhenBanMySortDetailFragment extends BaseFragment implements ClassifyNewAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener, ZhenBanSortLabelAdapter.OnItemClickListener, View.OnClickListener {

    private ClassifyNewAdapter mAdapter;


    TextView tv_total;
    CheckBox cb_check;
    RecyclerView recycle_liebiao;

    LinearLayoutManager linearLayoutManager;

    RecyclerView recycle_biaoqian;

    Button btn_submit;
    TextView text_del;
    List<ShopListModel.DataBean> data = new ArrayList<>();

    String token;
    private IntentFilter intentFilter;
    private MyBroadCast netWorkChangeReceiver;

    int myflag = 0;

    @Override
    public void onItemLabelClickListener(View view, int pos, List<ShopListModel.DataBean> myLiveList) {
        linkLabelAdapter.setCheckedPosition(pos);
        recycle_liebiao.scrollToPosition(pos);
    }


    private class MyBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //系统服务类
            String pos = intent.getStringExtra("pos");
            Log.d("pospospos", pos);
            if (data.size() > 0) {
                data.clear();
            }
            if (pos.equals("0")) {
                data.clear();
            } else {
                HttpResponse.getFenLeiShop(token, pos, new StringCallback(getActivity()) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d("getCodegetStr", s);
                        Gson gson = new Gson();
                        ShopListModel shopListModel = new ShopListModel();
                        shopListModel = gson.fromJson(s, ShopListModel.class);
                        data.addAll(shopListModel.getData());
                        mAdapter.setDataList(data);
                        linkLabelAdapter.setDataList(data);
                        if (data.size() == 0) {
                            layout_selectall.setVisibility(View.GONE);
                            layout_nodata.setVisibility(View.VISIBLE);
                            layout_all.setVisibility(View.GONE);
                        } else {
                            layout_selectall.setVisibility(View.VISIBLE);
                            layout_nodata.setVisibility(View.GONE);
                            layout_all.setVisibility(View.VISIBLE);
                        }
                        if (data.size() < 6) {
                            layout_more.setVisibility(View.INVISIBLE);
                        } else {
                            layout_more.setVisibility(View.VISIBLE);
                        }
                        popWindowCreate(data);
                    }
                });
            }

        }
    }

    private void init() {

        intentFilter = new IntentFilter();
        intentFilter.addAction("canting.chushizhang.ZhenBanMySortDetailFragment");
        netWorkChangeReceiver = new MyBroadCast();
        //注册广播
        getActivity().registerReceiver(netWorkChangeReceiver, intentFilter);
    }

    String date_Send;
    int select_shop = 0;
    ZhenBanSortLabelAdapter linkLabelAdapter;
    String receiveStr = "";
    LinearLayout layout_more;
    PopupWindowCompat popupWindow;
    LinearLayout layout_selectall;
    LinearLayout layout_nodata;
    LinearLayout layout_all;

    @Override
    public View initView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_sort_detail2, null);

        tv_total = (TextView) view.findViewById(R.id.tv_total);
        cb_check = (CheckBox) view.findViewById(R.id.cb_check);
        EventBus.getDefault().register(this);
        recycle_liebiao = view.findViewById(R.id.recycle_liebiao);
        recycle_biaoqian = view.findViewById(R.id.recycle_biaoqian);
        btn_submit = view.findViewById(R.id.btn_submit);
        layout_more = view.findViewById(R.id.layout_more);
        layout_all = view.findViewById(R.id.layout_all);
        layout_more.setOnClickListener(this);
        layout_nodata = view.findViewById(R.id.layout_nodata);
        layout_selectall = view.findViewById(R.id.layout_selectall);
        btn_submit.setOnClickListener(this);
        text_del = view.findViewById(R.id.text_del);
        Log.d("dkdkkd", "到这里了么");
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        receiveStr = getArguments().getString("right");
        getCanldaData();
        init();
        linkLabelAdapter = new ZhenBanSortLabelAdapter(getActivity(), data);
        Log.d("到这里了么", receiveStr);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        recycle_liebiao.setLayoutManager(linearLayoutManager);
        if (data.size() > 0) {
            data.clear();
        }
        mAdapter = new ClassifyNewAdapter(getActivity(), data);

        recycle_liebiao.setAdapter(mAdapter);
        final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 3);
        recycle_biaoqian.setLayoutManager(mLayoutManager);
        recycle_biaoqian.setAdapter(linkLabelAdapter);
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        linkLabelAdapter.setOnItemClickListener(this);
        Log.d("RIGHTRIGHT", receiveStr);
        mAdapter.setOnItemClickListener(this);
        cb_check.setOnCheckedChangeListener(this);
        getData();
        return view;
    }

    public void getData() {
        if (receiveStr.equals("0")) {
            if (data.size() > 0) {
                data.clear();
            }
        } else {
            HttpResponse.getFenLeiShop(token, "100", new StringCallback(getActivity()) {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Log.d("getCodegetStr", s);
                    if (data.size() > 0) {
                        data.clear();
                    }
                    Gson gson = new Gson();
                    ShopListModel shopListModel = new ShopListModel();
                    shopListModel = gson.fromJson(s, ShopListModel.class);
                    data.addAll(shopListModel.getData());
                    if (data.size() == 0) {
                        layout_selectall.setVisibility(View.GONE);
                        layout_nodata.setVisibility(View.VISIBLE);
                        layout_all.setVisibility(View.GONE);
                    } else {
                        layout_selectall.setVisibility(View.VISIBLE);
                        layout_nodata.setVisibility(View.GONE);
                        layout_all.setVisibility(View.VISIBLE);
                    }
                    if (data.size() < 6) {
                        layout_more.setVisibility(View.INVISIBLE);
                    } else {
                        layout_more.setVisibility(View.VISIBLE);
                    }
                    popWindowCreate(data);
                    mAdapter.setDataList(data);
                    linkLabelAdapter.setDataList(data);


                }
            });
        }
    }


    @Override
    public void initData() {

    }

    List<String> applyList = new ArrayList<>();


    @Override
    public void onItemClickListener(View view, int pos, List<ShopListModel.DataBean> myLiveList) {
        switch (view.getId()) {
            case R.id.checkbox:
            case R.id.layout_checkbox:
                if (myLiveList.get(pos).getApplyAmount() == 0) {
                    Toast.makeText(getActivity(), "请选择商品数量", Toast.LENGTH_SHORT).show();
                    myLiveList.get(pos).setChecked(false);
                    mAdapter.notifyDataSetChanged();
                } else {
                    for (ShopListModel.DataBean cart : data) {
                        if (cart.isChecked()) {   //是否勾上去了

                            Log.d("勾选上了", "勾选上了");

                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("commodityId", cart.getCommodityId());
                                jsonObject.put("commodityAmount", cart.getApplyAmount() + "");
                                jsonObject.put("categoryId", "0");
                                jsonObject.put("mark", cart.getMark());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            applyList.add(jsonObject.toString());
                            ToolList.removeDuplicateWithOrder(applyList);
                            tv_total.setText("已选购" + applyList.size() + "");
                            text_del.setVisibility(View.GONE);
                            Log.d("applyListapplyListapplyList", applyList.toString());

                            myflag = 0;
                            if (data.size() == applyList.size()) {
                                cb_check.setChecked(true);
                            }
                            Log.d("datasize", data.size() + "");
                            Log.d("applyList", applyList.size() + "");
                        } else {
                            Log.d("取消勾选", "取消勾选");
                            myflag = 1;
                            cb_check.setChecked(false);
                            if (applyList.size() > 0) {
                                for (int i = 0; i < applyList.size(); i++) {
                                    if (applyList.get(i).contains(cart.getCommodityId())) {
                                        applyList.remove(i);
                                    }
                                }
                                text_del.setVisibility(View.GONE);
                            } else if (applyList.isEmpty()) {
                                text_del.setVisibility(View.GONE);
                            } else if (applyList.size() == 0) {
                                text_del.setVisibility(View.GONE);
                            }

                            ToolList.removeDuplicateWithOrder(applyList);
                            Log.d("applyListapply", applyList.toString());
                            tv_total.setText("已选购" + applyList.size() + "");
                        }
                    }
                }

                break;
            case R.id.img_add:
            case R.id.tv_add:
            case R.id.tv_reduce:
                select_shop = myLiveList.get(pos).getApplyAmount();
                break;
            case R.id.text_beizhu:

                createPopwindow(pos, myLiveList);

                break;
            case R.id.img_collect:

                getCollect(token, pos, myLiveList.get(pos).getCommodityId(), myLiveList);

                break;

            case R.id.tv_num:
                payDialog3(pos, myLiveList);
                break;

        }
    }

    /**
     * 3 自定义方式
     */
    private void payDialog3(int pos, List<ShopListModel.DataBean> myLiveList) {
        final PayPassDialog dialog = new PayPassDialog(getActivity(), R.style.dialog_pay_theme);
        //弹框自定义配置
        dialog.setAlertDialog(false)
                .setWindowSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.4f)
                .setOutColse(false) //点击外部是否消失
                .setGravity(R.style.dialogOpenAnimation, Gravity.BOTTOM);
        //组合控件自定义配置
        dialog.getPayViewPass()
                .setHintText("数量")
                .setForgetText("密码忘记?")
                .setForgetColor(getResources().getColor(R.color.colorAccent))
                .setForgetSize(16)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String password) {
                        //6位输入完成回调
//                        Toast.makeText(mContext, "输入内容:" + password, Toast.LENGTH_SHORT).show();
                        Log.d("passwordpassword", password);

                        if (password.equals("")) {

                        } else {
                            Integer int_count = Integer.valueOf(password);
                            myLiveList.get(pos).setApplyAmount(int_count);
                            mAdapter.notifyDataSetChanged();
                        }


                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭回调
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();

                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(netWorkChangeReceiver);
    }

    public void getCanldaData() {
        Date date3 = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date3);
        calendar.add(Calendar.DATE, 1);//1表示明天,-1表示昨天
        date3 = calendar.getTime(); //这个时间就是明天
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter2.format(date3);
        System.out.println(dateString);
        Log.d("dateStringdateString", dateString);
        date_Send = dateString;
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            int flag = 0;
            myflag = 0;
            Log.d("applyListapplyList", applyList.toString());
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getApplyAmount() > 0) {
                    flag = data.get(i).getApplyAmount();
                }
            }
            if (flag == 0) {
                Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                cb_check.setChecked(false);
            } else {
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getApplyAmount() > 0) {
                        cb_check.setChecked(true);
                        data.get(i).setChecked(true);
                        text_del.setVisibility(View.GONE);
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("commodityId", data.get(i).getCommodityId());
                            jsonObject.put("commodityAmount", data.get(i).getApplyAmount() + "");
                            jsonObject.put("categoryId", "0");
                            jsonObject.put("mark", data.get(i).getMark());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        applyList.add(jsonObject.toString());
                        ToolList.removeDuplicateWithOrder(applyList);
                    } else {
                        data.get(i).setChecked(false);
                    }

                }
            }

            Log.d("AllSelectAllApplist", applyList.toString());
//                        showTotalPrice();
            tv_total.setText("已选购" + applyList.size() + "");
            mAdapter.notifyDataSetChanged();
        } else {
            if (myflag == 0) {
                for (int i = 0; i < data.size(); i++) {
                    data.get(i).setChecked(false);
                }
                applyList.clear();
                mAdapter.notifyDataSetChanged();
                Log.d("NoSelectAllApplist", applyList.toString());
                tv_total.setText("已选购" + applyList.size() + "");
            } else {

            }

        }
    }


    public void getCollect(String token, int pos, String commodityId, List<ShopListModel.DataBean> myLiveList) {
        HttpResponse.setCommodityCollect(token, commodityId, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                Log.d("setCommodityCollect", s);
                CommdityColletModel commdityColletModel = GsonUtil.GsonToBean(s, CommdityColletModel.class);
                myLiveList.get(pos).setCollectionFlag(commdityColletModel.getData().getData());
                mAdapter.notifyDataSetChanged();
                Toast.makeText(getActivity(), commdityColletModel.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if (applyList.size() == 0) {
                    Toast.makeText(mContext, "请选择商品", Toast.LENGTH_SHORT).show();
                } else {
                    submitData();

                }


                break;
            case R.id.layout_more:
//                Toast.makeText(getActivity(), "MoRe", Toast.LENGTH_SHORT).show();
                popupWindow.showAsDropDown(layout_more);
                break;
        }
    }

    public void createPopwindow(int pos, List<ShopListModel.DataBean> myLiveList) {
        MyLabelAdapter myLabelAdapter;
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

        View view1 = layoutInflater.inflate(R.layout.dialog_bottom, null);

        ButtomDialogView bottomSheetDialog = new ButtomDialogView(getActivity(), view1, true, true);
        bottomSheetDialog.setContentView(R.layout.toast_dialog);
        bottomSheetDialog.show();
        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        recycle_biaoqian.setLayoutManager(gridLayoutManager);
        EditText verify_et = view1.findViewById(R.id.verify_et);

        TextView text_submit = view1.findViewById(R.id.text_submit);
        myLabelAdapter = new MyLabelAdapter(getActivity());
        recycle_biaoqian.setAdapter(myLabelAdapter);
        List<String> mystr = new ArrayList<>();

        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        ImageView img_close = view1.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });

        HttpResponse.getMark(token, "4", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getMarkgetMark", s);

                GetMarkModel getMarkModel = new GetMarkModel();
                getMarkModel = GsonUtil.GsonToBean(s, GetMarkModel.class);
                for (int i = 0; i < getMarkModel.getData().size(); i++) {
                    mystr.add(getMarkModel.getData().get(i).getMark());
                    myLabelAdapter.setDataList(mystr);
                }

                myLabelAdapter.setOnItemClickListener(new MyLabelAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClickListener(View view, int pos, List<String> myLiveList) {
                        Log.d("ZHenBanMYsortDetail", myLiveList.get(pos));
                        myLabelAdapter.setCheckedPosition(pos);
                        verify_et.setText(myLiveList.get(pos));
                    }
                });
            }
        });

        text_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myLiveList.get(pos).setMark(verify_et.getText().toString());
                bottomSheetDialog.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });

    }


    public void popWindowCreate(List<ShopListModel.DataBean> myLiveList) {
        popupWindow = new PopupWindowCompat(getActivity());
        View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.zhenban_label, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setContentView(view1);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        recycle_biaoqian.setLayoutManager(gridLayoutManager);
        ZhenBanSortAllLabelAdapter zhenBanSortAllLabelAdapter = new ZhenBanSortAllLabelAdapter(getActivity(), myLiveList);
        recycle_biaoqian.setAdapter(zhenBanSortAllLabelAdapter);
        zhenBanSortAllLabelAdapter.setDataList(myLiveList);
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        zhenBanSortAllLabelAdapter.setOnItemClickListener(new ZhenBanSortAllLabelAdapter.OnItemClickListener() {
            @Override
            public void onItemLabelClickListener(View view, int pos, List<ShopListModel.DataBean> myLiveList) {
                zhenBanSortAllLabelAdapter.setCheckedPosition(pos);
                recycle_biaoqian.scrollToPosition(pos);
            }
        });
    }


    public void submitData() {
        List<String> mylist = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("commodityId", "商品1");
            jsonObject.put("commodityAmount", "10");
            jsonObject.put("categoryId", "0");
            jsonObject.put("mark", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject2 = new JSONObject();
        try {
            jsonObject2.put("commodityId", "商品1");
            jsonObject2.put("commodityAmount", "10");
            jsonObject2.put("categoryId", "0");
            jsonObject2.put("mark", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mylist.add(jsonObject.toString());
        mylist.add(jsonObject2.toString());
        Log.d("mylistmylistmylist", "dkdkdk");
        Log.d("DKkdkdkdk", jsonObject.toString());
        HttpResponse.submitData(token, date_Send, "1", applyList.toString(), "8点之前", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("SortDetailFragment", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    EventBus.getDefault().post(11);
                    EventBus.getDefault().post(15);
                    getActivity().finish();
                }
                Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void onEventMainThread(Integer integer) {


    }

}
